<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="<%=basePath %>/resource/js/common-css-js.js"></script>
<title>采购计划-添加</title>
<link type="text/css" rel="stylesheet" href="<%=basePath %>/resource/css/step.css">
<style type="text/css">
	body {
		margin: 10px;
	}

	legend {
		width: auto;
	    border-bottom: none;
	}
	
	.layui-field-box {
		padding: unset;
		padding-right: 15px;
	}
	
	.layui-form-select {
		padding-left: 10px;
	}
	
	.select-box {
		padding: 10px;
		padding-top: unset;
		padding-right: 20px;
	}
	
	.clean-m-buttom {
		margin-bottom: unset;
	}
	
	.layui-table-cell .layui-form-checkbox[lay-skin="primary"]{
	    top: 50%;
	    transform: translateY(-50%);
	}
	
	.magt0,
	.layui-table-view {
		margin: unset;
		margin-bottom: 10px;
	}
	
	.resultBox {
		height: 150px;
    	border: 1px solid #e2e2e2;
	}
	
	.p-style {
		font-size: 50px;
    	line-height: 140px;
	}
	
	.abstract-rightBottom {
		position: absolute;
	    right: 0px;
	    bottom: 0px;
	}
	
</style>
</head>
<body>
	<div id="step" class="step-body">
	    <div class="step-header step-header-wrap">
	    	<i id="preBtn" class="layui-icon stepBtn">&#xe603;</i>
	    	<i id="nextBtn" class="layui-icon stepBtn">&#xe602;</i>
	        <ul>
	            <li>
	                <span class="step-name">基本信息填写</span>
	            </li>
	            <li>
	                <span class="step-name">物品选着</span>
	            </li>
	            <li>
	                <span class="step-name">确认提交</span>
	            </li>
	        </ul>
	    </div>
	    <form id="formFilter" class="layui-form" lay-filter="formFilter">
    		<div class="step-content">
	        	<div class="step-list">
					<fieldset class="layui-elem-field">
					  <legend>必填信息</legend>
					  <div class="layui-field-box">
						  <div class="layui-form-item">
						    <label class="layui-form-label">采购单号</label>
						    <div class="layui-input-block">
						      <input type="text" name=procurePlanOrderNumber lay-verify="required|intNumber" autocomplete="off" placeholder="采购单号" class="layui-input">
						    </div>
						  </div>
						  <div class="layui-form-item">
						    <label class="layui-form-label">采购主题</label>
						    <div class="layui-input-block">
						      <input type="text" name="procurePlanTheme" lay-verify="required" autocomplete="off" placeholder="采购主题" class="layui-input">
						    </div>
						  </div>
						  <div class="layui-form-item">
						    <label class="layui-form-label">计划员</label>
						    <div class="layui-input-block">
						      <input type="text" name="procurePlanPlanner" lay-verify="required|peopleName" lay-verify="title" autocomplete="off" placeholder="计划员" class="layui-input">
						    </div>
						  </div>
						  <div class="layui-form-item">
						    <label class="layui-form-label">采购员</label>
						    <div class="layui-input-block">
						      <input type="text" name="procurePlanBuyer" lay-verify="required|peopleName" autocomplete="off" placeholder="采购员" class="layui-input">
						    </div>
						  </div>
						  <div class="layui-form-item">
						    <label class="layui-form-label">采购日期</label>
						    <div class="layui-input-block">
						      <input id="startDatetime" type="text" layui-verify="required|date" name="procurePlanStartDate" placeholder="采购日期" class="layui-input">
						    </div>
						  </div>
						  <div class="layui-form-item">
						    <label class="layui-form-label">截止日期</label>
						    <div class="layui-input-block">
						      <input id="endDatetime" type="text" layui-verify="required|date" name="procurePlanEndDate" placeholder="截止日期" class="layui-input">
						    </div>
						  </div>
					  </div>
					</fieldset>
			   	</div>
        		<div class="step-list">
        			<fieldset class="layui-elem-field">
						<legend>选择供应商</legend>
						<div class="layui-form-item clean-m-buttom">
							<div class="layui-row select-box"> 
							    <div class="layui-col-md4 layui-col-xs4">
							      <select id="supplierLv" name="supplierLv" lay-verify="required" lay-filter="supplierLv">
							      	<option value="">请选择-供应商级别</option>
							      </select>
							    </div>
							    <div class="layui-col-md4 layui-col-xs4">
							      <select id="supplierClass"  name="supplierClass" lay-verify="required" lay-filter="supplierClass">
							      	<option value="">请选择-供应商分类</option>
							      </select>
							    </div>
							    <div class="layui-col-md4 layui-col-xs4">
							      <select id="supplierArchives" name="supplierArchives" lay-verify="required" lay-filter="supplierArchives">
							      </select>
							    </div>
						    </div>
						</div>
		        	</fieldset>
		        	<table id="productTable" lay-filter="productTable"></table>
	        	</div>
        		<div class="step-list">
        			<div class="layui-row layui-col-space10">
						<div class="layui-col-lg6 layui-col-md6">
							<blockquote class="layui-elem-quote title">基本信息预览</blockquote>
							<table class="layui-table magt0">
								<colgroup>
									<col width="150">
									<col>
								</colgroup>
								<tbody id="baseInfo">
								</tbody>
							</table>
							<div class="layui-col-lg12 layui-col-md12">
								<blockquote class="layui-elem-quote title">计算结果</blockquote>
								<div class="resultBox">
									<p class="p-style">总款核算:
										<span id="calculation"></span><span>元</span>
									</p>
								</div>
								<input class="layui-btn layui-btn-normal abstract-rightBottom" type="submit" value="添加该采购计划" lay-submit lay-filter="submitForm"/>
							</div>
						</div>
						<div class="layui-col-lg6 layui-col-md6">
							<blockquote class="layui-elem-quote title">选中产品预览</blockquote>
							<table class="layui-table magt0" lay-data="{id:'selectedProductTable',height: 'full'}" lay-filter="selectedProductTable">
								<thead>
								    <tr>
								      <th lay-data="{field: 'productNameView', minWidth: '140'}">名称</th>
								      <th lay-data="{field: 'unitPriceView', sort: true, minWidth: '140'}">单价</th>
								      <th lay-data="{field: 'countView', sort: true, edit: 'text', minWidth: '140'}">数量</th>
								      <th lay-data="{field: 'totalView', sort: true, minWidth: '135'}">总价</th>
								    </tr>
							  	</thead>
								<tbody id="productInfo">
								</tbody>
							</table>
						</div>
					</div>
        		</div>
	        </div>
	    </form>
	</div>
	<script type="text/javascript">
	
		layui.use('steps',function(){
			var $step = $("#step").step();
			//导航步骤组建
			$("#preBtn").click(function(event) {
				$step.preStep();//上一步
			});
			$("#nextBtn").click(function(event) {
				//如果下一页是最后一页着进行确认页面的渲染
				if($step.getCurPage()==2){
					randerConfirmPage();
				}
				$step.nextStep();//下一步
			});
			$("#startBtn").click(function(event) {
				$step.goStep(1);//到指定步
			});
		})
		
		//时间选择器-采购日期           
		laydate.render({                
		  elem: '#startDatetime,#endDatetime'        
		  ,type: 'datetime'             
		});                             
		/* //时间选择器-截止日期           
		laydate.render({                
		  elem: '#endDatetime'          
		  ,type: 'datetime'             
		});    */                          
	
		//标记之前是否已经生成了dom结构
		var flag = true;
		/**
		 *渲染确认提交页面
		 *这里需要接受一个layui的table模块对象
		 */
		function randerConfirmPage(){
			// 用来记算所有商品的总价格
			var itemsCountPrise = 0;
			//获取用来显示所有商品总价格
			var calculationEle = $("#calculation");
			//获取展示基本信息表格tbody
			var baseInfoEle = $("#baseInfo");
			//获取选中的产品信息展示区域
			var productInfoEle = $("#productInfo");
		    //获取序列化后的数据,Json格式 name:value
			var dataArray = {};
		    var serializeArray = $('#formFilter').serializeArray();
		    //获取form表单中的label标签
		    var labels = $(".layui-form-label");
		    //在生成基本信息展示之前,先清除之前的!
		    baseInfoEle.children().remove();
		    //获取label标签中的文本
		    for(var itemLabel = 0;itemLabel<labels.length;itemLabel++){
		    	//进行dom结构的生成
		    	baseInfoEle.append(
		    			"<tr>"+
		    				"<td>"+labels[itemLabel].innerText+"</td>"+
		    				"<td>"+serializeArray[itemLabel].value+"</td>"+
		    			"</tr>"
		    	);
		    }
		    //获取表格中选中的数据
		    var checkStatus = table.checkStatus('productTable');
		    
		    //判断是否已经存在选中产品
		    if(flag){
		    	//在生成之前,先清空之前的dom子节点
			    productInfoEle.children().remove();
			    //循环遍历选中的产品
			    for(var item_product = 0;item_product<checkStatus.data.length;item_product++){
			    	//循环生成dom,并添加上去!
			    	productInfoEle.append(
				    		"<tr>"+
			    				"<td>"+checkStatus.data[item_product].prodName+"</td>"+
			    				"<td>"+checkStatus.data[item_product].prodPrice+"</td>"+
			    				"<td></td>"+
			    				"<td></td>"+
			    			"</tr>"
			        );
			    }
			    
			 	// 将表格转换为静态表格
			    table.init('selectedProductTable', {
		    	  height: 315 //设置高度
		    	  ,limit: 10 //注意：请务必确保 limit 参数（默认：10）是与你服务端限定的数据条数一致
		    	}); 
			 	
			    flag = false;
		    }
				
			//开启表格中的行内编辑功能
		    table.on('edit(selectedProductTable)', function(obj){
			  // 获取对应的总价元素
			  var totalViewEle =  $("tr[data-index='"+obj.data.LAY_TABLE_INDEX+"'] td[data-field='totalView'] div");
			  var totalPrice = obj.value*obj.data.unitPriceView;
			  itemsCountPrise = itemsCountPrise + totalPrice;
			  totalViewEle.text(totalPrice);
			  calculationEle.text(itemsCountPrise);
		  	});
	 	}
	
	//物品选着
		//渲染供应商级别<select>
		renderSelectOption($("#supplierLv"),"/supplier-lv");
		/*渲染表格,但是不做数据查询*/
	  	table.render({
		    elem: '#productTable'
		    ,height: 315
		    ,cellMinWidth: 80
	  		,page: true
	  		,limits: [10,50,100]
		    ,cols: [[
		    	{type:'checkbox',align: 'center'},
		    	{field:'prodName',title:'品名',align: 'center'},
		    	{field:'prodModel',title:'型号',align: 'center'},
		    	{field:'prodSpecifications',title:'规格',align: 'center'},
		    	{field:'prodSize',title:'尺寸',align: 'center'},
		    	{field:'prodWeight',title:'重量',align: 'center'},
		    	{field:'prodMaterials',title:'用料',align: 'center'},
		    	{field:'prodType',title:'种类',align: 'center'},
		    	{field:'prodUnit',title:'单位',align: 'center'},
		    	{field:'prodImportFlag',title:'是否进口',align: 'center'},
		    	{field:'prodPrice',title:'价格',align: 'center'}
		    ]]
		  	,text: {
			   none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
			}
	    });
		
		//监听供应商分类
		form.on('select(supplierClass)', function(data){
		  var supplierLv = $("#supplierLv").val()
		  var supplierArchives = $("#supplierArchives");
			  if(supplierLv==""){
				  fixedAlert("请选择一个供应商等级!",0);
			  }else {
				  //在另外进行分类的选着时,清除之前已有的数据
				  $("div[class='layui-table-body layui-table-main']").children().remove();
				  //当两个都不为空的时,发送ajax请求,加载第三个选项
				  $.ajax({//发送ajax请求查询供应商
					   type: 'GET',
					   url: path+"/procurement/supplier-archives/"+supplierLv+"-"+data.value,
					   contentType: "application/x-www-form-urlencoded;charset='UTF-8'", 
					   success: function(msg){
						   supplierArchives.children().remove();
						   if(msg.length<=0){
							   supplierArchives.append('<option value="">没有该分类的供应商</option>');
						   }else{
							   supplierArchives.append('<option value="">请选择-指定供应商</option>');
							   for(var i = 0;i<msg.length;i++){
								   supplierArchives.append("<option value="+msg[i].supArchiId+">"+msg[i].supArchiEnterpriseName+"</option>");
							   }
						   }
						   form.render('select');
					   }
				  });
			  }
		});
		
		//监听供应商级别
		form.on('select(supplierLv)', function(data){
			var supplierClass = $("#supplierClass");
			var supplierArchives = $("#supplierArchives");
			//先删除供应商下面的所有节点
			supplierClass.children().remove();
			//添加回一个子节点
			supplierClass.append('<option value="">请选择-供应商分类</option>');
			if(data.value!=""){
				renderSelectOption(supplierClass,"/supplier-classification");
			}
			supplierArchives.children().remove();
			form.render('select');
		})
		
		//监听具体的供应商
		form.on('select(supplierArchives)', function(data){
			var supplierArchives = $("#supplierArchives");
			if(data.value == ""){
				//如果为空着给定一个默认值
				data.value = 0;
				supplierArchives.append('<option value="">没有该分类的供应商</option>');
			}
			table.reload('productTable', {
				url: path+'/procurement/production-prise/'+data.value //数据接口
				,request: {
			  	   pageName: 'offset' //页码的参数名称，默认：page
			  	  ,limitName: 'limit' //每页数据量的参数名，默认：limit
			  	}
			  	,response: {
			  	  statusName: 'code' //数据状态的字段名称，默认：code
			  	  ,statusCode: 200 //成功的状态码，默认：0
			  	  ,msgName: 'msg' //状态信息的字段名称，默认：msg
			  	  ,countName: 'total' //数据总数的字段名称，默认：count
			  	  ,dataName: 'rows' //数据列表的字段名称，默认：data
			  	}
			});
		})
		table.on('checkbox(productTable)', function(obj){
			//当产品重新选着时，将锁打开，重新生成dom
			flag = true;
		});
		
		//渲染第三个页面
		//提交数据
		form.on('submit(submitForm)', function(data){
		  //获取对应的供应商
		  data.field.prodSupplierId = $("#supplierClass").val();
		  //获取选中的产品
		  var checkStatus = table.checkStatus('productTable');
		  //添加总款价格
		  data.field.procurePlanAmountBudget = $("#calculation").text();
		  //获取产品采购的数量,更具获取到的选中行来生成选着器,获取到对应的数量
		  for(var index = 0;index<checkStatus.data.length;index++){
			  //定位到存储数量的dom中,获取它的值,添加到对象中
			  checkStatus.data[index].buyCount = 
				  $("tr[data-index="+index+"] td[data-field='countView'] > div").text();
		  }
		  //将两个对象合并成一个对象,方便传递
		  var object = $.extend(data.field, checkStatus);
		  
		  $.ajax({
			   type: 'POST',
			   url: "<%=basePath%>/procurement/procurement-plan?method=add",
			   data: JSON.stringify(object),
			   contentType: "application/json;charset='UTF-8'", 
			   statusCode: {
				   201: function() {
					   fixedAlert("添加采购计划！",1,true,true);
				   },
				   400: function(){
					   fixedAlert("添加失败,请检查输入的值是否非法操作！",0,false);
				   },
				   500: function(){
					   fixedAlert("服务端繁忙！",2,false);
				   }
			   },
	      });
		  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
		});
	</script>
</body>
</html>